package pers.vic.boot.security.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pers.vic.boot.security.jwt.AuthorityInfo;
import pers.vic.boot.security.jwt.JwtService;
import pers.vic.boot.security.jwt.JwtToken;
import pers.vic.boot.security.jwt.JwtUtil;
import pers.vic.boot.security.jwt.enums.JwtVerifyEnum;

/**
 * @description: 认证策略 
 * 在doGetAuthorizationInfo方法中把用户的权限设置进去,以配合controller的方法的注解对操作
 * 进行拦截. 用户的权限可以考虑在login的时候 以token为key存储在REDIS中,
 * 也可以在构造token的时候把信息存入token
 * @author: Vic.xu
 * @date: 2019年12月31日 上午11:50:13
 */
public class MyRealm extends AuthorizingRealm {

    protected static final Logger LOGGER = LoggerFactory.getLogger(MyRealm.class);

    private JwtService jwtService;
    
    public MyRealm(JwtService jwtService) {
    	this.jwtService = jwtService;
    }

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	String token = principals.toString();
        AuthorityInfo info = jwtService.getAuthorityInfo(token);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(info.getRoles());
        simpleAuthorizationInfo.addStringPermissions(info.getPermission());
        LOGGER.info("doGetAuthorizationInfo:{}", info);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。 SecurityUtils.getSubject().login的时候被调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        JwtVerifyEnum verify = jwtService.verify(token);

        if (JwtVerifyEnum.SUCCESS != verify) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
